export const compressImg = (file, options = {}) => {
  const { maxiSzie = 100 * 1024, maxWidth = 1920, quality = 0.8 } = options;

  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    const img = new Image()

    
    reader.onload = (e) => {
      const result = e.target.result
      img.src = result

      img.onload = () => {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')

        // 计算比例
        const scale = Math.min(maxWidth / img.width, 1)
        canvas.width = img.width * scale
        canvas.height = img.height * scale

        // 将图片放置画布
        ctx.imageSmoothingQuality = 'high'
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height)

        // 压缩图片
        let addquality = quality
        const compress = (compressQuality) => {
          return new Promise((compressResolve) => {
            canvas.toBlob((blob) => {
              if (!blob) return reject(new Error('文件压缩失败'))
              
              // 比设定大，需要进一步压缩
              if (blob.size > maxiSzie) {
                addquality = addquality - 0.05
                compress(addquality).then(compressResolve)
              }
              else {
                compressResolve(blob)
              }
              
            }, 'image/jpeg', compressQuality)
          })
        }

        compress(quality)
          .then((blob) => {
            resolve(blob)
          })
          .catch(() => {
            reject(new Error('文件压缩失败'))
          })
      }

      img.onerror = (error) => { reject('图片加载失败')}
    }

    reader.onerror = (error) => { reject(new Error(error))}
    reader.readAsDataURL(file)
  })
}


export const fileToBlob = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = (e) => {
      const result = e.target.result
      const blob = new Blob([result], {type: file.type})
      resolve(blob)
    }
    reader.onerror = () => { reject('fileToBlob失败')}
  })
}
export const blobToFile = (blob, fileName) => {
  const file = new File([blob], fileName, {type: blob.type})
  return file
}